/**
 * 获取需要滚动的元素
 * @param el
 * @param ref
 * @returns {null}
 */
export const getParentScroll = (el, ref='appScrollbar') => {
    let tempEle = null
    while (el) {
        if (el.$refs.appScrollbar) {
            tempEle = el.$refs.appScrollbar.wrap
        }
        el = el.$parent
    }
    return tempEle
}
// 运动方式
let easeInOutQuad = function(t, b, c, d) {
    t /= d / 2
    if (t < 1) {
        return c / 2 * t * t + b
    }
    t--
    return -c / 2 * (t * (t - 2) - 1) + b
}

// 兼容动画帧
let requestAnimFrame = (function () {
    return window.requestAnimationFrame
    || window.webkitRequestAnimationFrame
    || function (callback) {window.setTimeout(callback, 1000 / 60)}
})()
// 移动
const move = (ele, amount, key) => {
    if (key) {
        ele.style.transform = 'translateY('+ (amount) +'px)'
    } else {
        ele.scrollTop = amount
    }
}
export const scrollTo = (ele ,to, duration, key, keyStart, callback) => {
    const start = keyStart ? keyStart : ele.scrollTop
    const change = to - start
    const increment = 20
    let currentTime = 0
    duration = (typeof (duration) === 'undefined') ? 500 : duration

    let animateScroll = function () {
        currentTime += increment
        let distance = easeInOutQuad(currentTime, start, change, duration)
        move(ele, distance, key)
        if (currentTime < duration) {
            requestAnimationFrame(animateScroll)
        } else {
            if (callback && typeof (callback) === 'function') {
                callback()
            }
        }
    }
    animateScroll()
}
const moveLeft = (ele, amount, key) => {
    if (key) {
        ele.style.transform = 'translateY('+ (amount) +'px)'
    } else {
        ele.scrollLeft = amount
    }
}
export const scrollToLeft = (ele ,to, duration, key, keyStart, callback) => {
    const start = keyStart ? keyStart : ele.scrollLeft
    const change = to - start
    const increment = 20
    let currentTime = 0
    duration = (typeof (duration) === 'undefined') ? 500 : duration

    let animateScroll = function () {
        currentTime += increment
        let distance = easeInOutQuad(currentTime, start, change, duration)
        moveLeft(ele, distance, key)
        if (currentTime < duration) {
            requestAnimationFrame(animateScroll)
        } else {
            if (callback && typeof (callback) === 'function') {
                callback()
            }
        }
    }
    animateScroll()
}
